//
//  CloseOrderViewController.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-24.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "CloseOrderViewController.h"
#import "OrderBaseInfo.h"
#import "ImageButton.h"
#import "Order.h"
#import "GoodDetailWebViewController.h"
#import "CutomButtonLikeAppstoreInstelButton.h"
#import "CONSTS.h"
#import "URLFactory.h"

@interface CloseOrderViewController() 

- (void)cancelModal;
- (void)closeMainOrder;
- (void)closeSonOrder:(UIButton *)sender;
- (void)closeOrderBy:(NSString *)tid_ reason:(NSString *)reason_;
- (void)closeIsEnd:(TaoBaoServer *)closeTaoBaoSever_;

@end

@implementation CloseOrderViewController

@synthesize  orderBaseInfo                  =               _orderBaseInfo;
@synthesize tableView                       =               _tableView;
@synthesize closeTaoBaoSever                =               _closeTaoBaoSever;

- (void)dealloc
{
    LF_RELEASE_SAFELY(_orderBaseInfo);
    LF_RELEASE_SAFELY(_closeTaoBaoSever);
    
    [_tableView release];
    [super dealloc];
}

- (id)initWithOrderBaseInfo:(OrderBaseInfo *)orderBaseInfo_
{
    self = [super init];
    if (self)
    {
        self.orderBaseInfo = orderBaseInfo_;
    }
    
    return self;
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"关闭交易";
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle: @"完成" 
                                                                              style: UIBarButtonItemStylePlain
                                                                             target: self 
                                                                             action: @selector(cancelModal)] autorelease];
    
    if ([_orderBaseInfo.orders count] > 1)
    {
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle: @"全部关闭" 
                                                                                   style: UIBarButtonItemStylePlain
                                                                                  target: self 
                                                                                  action: @selector(closeMainOrder)] autorelease];
    }
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}



#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.orderBaseInfo.orders count];
}

#define kcloseSonOrderButtn_tag 401
#define kShowCloseSonOrderButtn_tag 402
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *cellIdentifier = @"cellSign";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) 
    {
        NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"CloseOrderCell" owner: nil options: nil];
        cell = [cellArray objectAtIndex: 0];
        
        ImageButton *imageButton = (ImageButton *)[cell viewWithTag: 102];
        imageButton.layer.cornerRadius = 70.0;
        imageButton.layer.shadowColor = [UIColor blackColor].CGColor;
        imageButton.layer.shadowOpacity = 0.3;
        imageButton.layer.shadowOffset = CGSizeMake(4, 5);
        
        
        CutomButtonLikeAppstoreInstelButton *closeSonOrderButtn = [CutomButtonLikeAppstoreInstelButton buttonWithType: UIButtonTypeCustom];
        closeSonOrderButtn.frame = CGRectMake(250, 29, 64, 28);
        closeSonOrderButtn.indexPahtForCell = indexPath;
        closeSonOrderButtn.normalImage = [UIImage imageNamed: @"close_order1.png"];
        closeSonOrderButtn.actionImage = [UIImage imageNamed: @"close_order2.png"];
        closeSonOrderButtn.normalTitle = @"关闭交易";
        closeSonOrderButtn.actionTitle = @"确认关闭订单";
        closeSonOrderButtn.actionSel = @selector(closeSonOrder:);
        closeSonOrderButtn.delegate = self;
        closeSonOrderButtn.tag = kcloseSonOrderButtn_tag;
        [cell.contentView addSubview: closeSonOrderButtn];
        
        
        CutomButtonLikeAppstoreInstelButton *showCloseSonOrderButtn = [CutomButtonLikeAppstoreInstelButton buttonWithType: UIButtonTypeCustom];
        showCloseSonOrderButtn.frame = CGRectMake(250 - (91 - 63), 29, 91, 28);
        showCloseSonOrderButtn.indexPahtForCell = indexPath;
        showCloseSonOrderButtn.normalImage = [UIImage imageNamed: @"close_order2.png"];
        showCloseSonOrderButtn.actionImage = [UIImage imageNamed: @"close_order1.png"];
        showCloseSonOrderButtn.normalTitle = @"订单已关闭";
        showCloseSonOrderButtn.actionTitle = @"确认关闭订单";
        showCloseSonOrderButtn.actionSel = @selector(closeSonOrder:);
        showCloseSonOrderButtn.userInteractionEnabled = NO;
        showCloseSonOrderButtn.delegate = self;
        showCloseSonOrderButtn.tag = kShowCloseSonOrderButtn_tag;
        showCloseSonOrderButtn.hidden = YES;
        
        [cell.contentView addSubview: showCloseSonOrderButtn];
    }
    
    NSInteger row = [indexPath row];
    Order *order = [self.orderBaseInfo.orders objectAtIndex: row];
    UILabel *titlLabel = (UILabel *)[cell viewWithTag: 101];
    titlLabel.text = order.title;
    
    CGSize size = bubbleView( titlLabel.text, titlLabel.font, titlLabel.frame.size.width);
    titlLabel.frame = CGRectMake(titlLabel.frame.origin.x, 
                                 titlLabel.frame.origin.y, 
                                 titlLabel.frame.size.width, 
                                 size.height);
    
    ImageButton *button = (ImageButton *)[cell viewWithTag: 102];
    [button addTarget: self action: @selector(viewGoodDetail:) forControlEvents: UIControlEventTouchUpInside];
    NSURL *url = [NSURL URLWithString: order.pic_path];
    [button setImageWithURL: url placeholderImage: [UIImage imageNamed: @"goodPic.jpeg"]];
    button.num_iid = order.num_iid;
    
    CutomButtonLikeAppstoreInstelButton *closeSonOrderButtn = (CutomButtonLikeAppstoreInstelButton *)[cell viewWithTag: kcloseSonOrderButtn_tag];
    closeSonOrderButtn.indexPahtForCell = indexPath;
    if ([order.status isEqualToString: TRADE_CLOSED_BY_TAOBAO])
    {
        closeSonOrderButtn.hidden = YES;
        
            CutomButtonLikeAppstoreInstelButton *showCloseSonOrderButtn = (CutomButtonLikeAppstoreInstelButton *)[cell viewWithTag: kShowCloseSonOrderButtn_tag];
        showCloseSonOrderButtn.hidden = NO;
        
    }else
    {
        closeSonOrderButtn.hidden = NO;
        
        CutomButtonLikeAppstoreInstelButton *showCloseSonOrderButtn = (CutomButtonLikeAppstoreInstelButton *)[cell viewWithTag: kShowCloseSonOrderButtn_tag];
        showCloseSonOrderButtn.hidden = YES;
    }
    
    return cell;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    
    NSArray *cellArray = [[NSBundle mainBundle] loadNibNamed: @"CloseOrderCell" owner: nil options: nil];
    UITableViewCell *cell = [cellArray objectAtIndex: 0];
    UILabel *titleLabel = (UILabel *)[cell viewWithTag: 101];
    
    Order *order = [self.orderBaseInfo.orders objectAtIndex: row];
    NSString *title = order.title;
    CGSize size = bubbleView( title, titleLabel.font, titleLabel.frame.size.width);
    
    ImageButton *button = (ImageButton *)[cell viewWithTag: 102];
    
    float returnHeight = 0;
    if (button.frame.size.height > size.height)
    {
        returnHeight = button.frame.size.height;
    }else
    {
        returnHeight = size.height;
    }
    
    return returnHeight + titleLabel.frame.origin.y * 2;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
    button.userInteractionEnabled = NO;
    button.titleLabel.font = [UIFont systemFontOfSize: 14];
    button.titleLabel.textAlignment = UITextAlignmentLeft;
    [button setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
    
    UIImage *image = nil;
    if (0 == section)
    {
        image = [UIImage imageNamed: @"cell_section_header_view_top.png"];
        
    }else
    {
        image = [UIImage imageNamed: @"cell_section_header_view_middle.png"];
    }
    [button setBackgroundImage: image forState: UIControlStateNormal];
    
    [button setTitle: @"全部子订单" forState: UIControlStateNormal];
    
    return button;
}

#pragma mark - 自定义函数
- (void)cancelModal
{
    [self.navigationController dismissModalViewControllerAnimated: YES];
}

- (void)viewGoodDetail:(ImageButton *)sender
{
    NSString *num_iid = sender.num_iid;
    GoodDetailWebViewController *goodDetailWebViewController = [[[GoodDetailWebViewController alloc] initWithNum_iid: num_iid] autorelease];
    
    [self.navigationController pushViewController: goodDetailWebViewController animated: YES];
}

- (void)closeMainOrder
{
    _order = nil;
    
    NSString *tid = _orderBaseInfo.tid;//主订单的编号
    [self closeOrderBy: tid reason: GUAN_BI_LI_YOU];
}

- (void)closeSonOrder:(UIButton *)sender
{
    CustomButtonWithSign *button = (CustomButtonWithSign *)sender;
    NSInteger row = [button.indexPahtForCell row];
    
    _order = ((Order *)[_orderBaseInfo.orders objectAtIndex: row]);
    NSString *oid = _order.oid;//子订单的编号
    
    [self closeOrderBy: oid reason: GUAN_BI_LI_YOU];
}

- (void)closeOrderBy:(NSString *)tid_ reason:(NSString *)reason_
{
    NSString *closeOrderUrl = [URLFactory get_taobao_trade_close: reason_ tid:  tid_];
    
    ITTDINFO(@"%@", closeOrderUrl);
    
    self.closeTaoBaoSever = [[[TaoBaoServer alloc] initWithUrl: closeOrderUrl
                                                        object: self 
                                            requestIsEndSelect: @selector(closeIsEnd:)
                                           requestIsFailSelect: nil 
                                                  showWaitView: YES 
                                                     urlEncode: NO] autorelease];
    
    [self.closeTaoBaoSever startAsynchronousRequest];
}

- (void)closeIsEnd:(TaoBaoServer *)closeTaoBaoSever_
{
    ITTDINFO(@"%@", closeTaoBaoSever_.dic);
    BOOL successSign = verifyServerRetunSuccess( closeTaoBaoSever_.dic );
    if (successSign)
    {
        /*
         {"trade_close_response": {"trade": {"modified": "2010-05-11 10:39:33","tid": 22328010090301}}}
         
         */
        showAlert(ALERT_TITLE,  @"成功关闭订单");
        
        if (!_order)
        {
            self.navigationItem.rightBarButtonItem.enabled = NO;
            self.navigationItem.rightBarButtonItem = nil;
            _orderBaseInfo.status = TRADE_CLOSED_BY_TAOBAO;
            [_tableView reloadData];
            
            for (Order *order in _orderBaseInfo.orders)
            {
                order.status = TRADE_CLOSED_BY_TAOBAO;
            }
        }else
        {
            _order.status = TRADE_CLOSED_BY_TAOBAO;
            [_tableView reloadData];
        }
        
    }else
    {
        //{"error_response":{"code":520,"msg":"Remote service error","sub_code":"isv.invalid-parameter:tid","sub_msg":"交易已经被关闭[120727806057978]"}}
        NSString *reason = [[closeTaoBaoSever_.dic objectForKey: @"error_response"] objectForKey: @"sub_msg"];
        if (reason)
        {
            showAlert(ALERT_TITLE,  reason);
        }else
        {
            showAlert(ALERT_TITLE, ALERT_MESSAGE);
        }
    }
}

@end
